package com.course.utils.web;

import android.os.Handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baselib.android.utils.Logger;
import com.course.config.UrlConfig;
import com.course.model.HttpConfigBean;
import com.course.model.req.BaseReq;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HttpReq {

    static HttpReq instance;

    public static HttpReq getInstance() {
        if (instance == null) {
            instance = new HttpReq();
        }
        return instance;
    }

    public void post(int actionIndex, Map<String, Object> map, HttpRespCallBack callback) {
        HttpConfigBean configBean = HttpManager.getHttpConfig(actionIndex);
        if (configBean == null) {
            return;
        }
        Logger.d("initData1"+JSONObject.toJSONString(map));

        callback.onReqStart(configBean);
        String url = UrlConfig.getInstance().getUrl() + configBean.getAction();
        Logger.e(url);
        OkHttpUtils.post(url, map == null ? "" : JSON.toJSONString(map), new HttpCallBack(configBean, callback));
    }

    public class HttpCallBack implements Callback {
        HttpRespCallBack callback;
        HttpConfigBean configBean;
        Handler handler = new Handler();


        public HttpCallBack(HttpConfigBean configBean, HttpRespCallBack callback) {
            this.callback = callback;
            this.configBean = configBean;

        }

        @Override
        public void onFailure(Call call, IOException e) {
            call.cancel();
            Logger.d("onFailure");

            handler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        callback.onReqFail(configBean, e, "网络错误");
                        callback.onReqFinish(configBean);
                    } catch (Exception e) {
                        Logger.e(e);
                    }
                }
            });
        }

        @Override
        public void onResponse(Call call, Response response) {
            try {
                if (response.code() != 200) {
                    onFailure(call, new IOException());
                    return;
                }
                String result = response.body().string();
                Logger.d("onResponse"+result);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        int errorCode = jsonObject.getIntValue("errorCode");
                        if (errorCode != 0) {
                            String errorMsg = jsonObject.getString("errorMsg");
                            callback.onReqFail(configBean, new Exception(), errorMsg);
                            callback.onReqFinish(configBean);
                            return;
                        }
                        Object object = jsonObject.get("data");
                        if (object instanceof String) {
                            callback.onSuccess(configBean, false, object);
                            return;
                        }
                        Object data = jsonObject.get("data");

                        boolean isPageReq = false;
                        if (data instanceof JSONArray){
                            isPageReq =true;
                        }else if (data instanceof JSONObject){
                            JSONObject js = (JSONObject)data;
                            if (js.containsKey("total")){
                                isPageReq =true;
                            }
                        }else {
                            isPageReq =true;
                        }
                        // 列表数据
                        callback.onSuccess(configBean, isPageReq, data);

                    }
                });

            } catch (IOException e) {
                onFailure(call, e);
                return;
            }

            callback.onReqFinish(configBean);
        }
    }


}
